package org.heart.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.heart.entity.dto.UserBaseInfo;
import org.heart.mapper.UserBaseInfoMapper;
import org.heart.service.IUserBaseInfoService;
import org.heart.utils.ServerConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户基本信息表 服务实现类
 * </p>
 *
 * @author lml
 * @since 2025-06-16
 */
@Service
@Slf4j
public class UserBaseInfoServiceImpl extends ServiceImpl<UserBaseInfoMapper, UserBaseInfo> implements IUserBaseInfoService {

    @Resource
    private UserBaseInfoMapper lUserBaseInfoMapper;

    @Resource
    private ServerConfig serverConfig;

    @Override
    public UserBaseInfo loginOrRegister(UserBaseInfo lUserBaseInfo) {

        if(ObjectUtil.isNull(lUserBaseInfo.getOpenid())){
            log.info("openId 为空，登录失败！");
            return null;
        }

        QueryWrapper<UserBaseInfo> qw = new QueryWrapper<>();
        qw.eq("openid",lUserBaseInfo.getOpenid());
        List<UserBaseInfo> userList = lUserBaseInfoMapper.selectList(qw);

        if(ObjectUtil.isEmpty(userList)){
            log.info("用户不存在，直接注册新用户");

            UserBaseInfo user =  new UserBaseInfo();
            user.setRegisterTime(new Date());
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(serverConfig.getUrl());
            BeanUtils.copyProperties(lUserBaseInfo,user);

            lUserBaseInfoMapper.insert(user);

            return user;
        }else{
            log.info("用户信息已存在");
            UserBaseInfo user =  userList.get(0);
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(serverConfig.getUrl());

            lUserBaseInfoMapper.updateById(user);
            return userList.get(0);
        }
    }
}
